//
//  TencentApiManager.m
//  KwSing
//
//  Created by yuchenghai on 14-9-30.
//  Copyright (c) 2014年 kuwo.cn. All rights reserved.
//

#import "TencentApiManager.h"
#import "TencentOAuth.h"
#import "QQApi.h"
#import "QQApiInterface.h"
#import "SGAppDelegate.h"

@interface TencentApiManager () <TencentSessionDelegate, QQApiInterfaceDelegate>

@end

@implementation TencentApiManager
{
    TencentOAuth *_tencentAuth;
}

+ (id)defaultManager {
    static TencentApiManager *qqMgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        qqMgr = [[TencentApiManager alloc] init];
    });
    return qqMgr;
}

- (id)init {
    self = [super init];
    if (self) {
        _tencentAuth = [[TencentOAuth alloc] initWithAppId:QQAppID andDelegate:self];
        [[SGAppDelegate appDelegate] setQqApiInterfaceDelegate:self];
    }
    return self;
}

- (void)shareInAPP:(KSShareToQQType)shareToQQType title:(NSString *)title url:(NSString *)url description:(NSString *)description imageUrl:(NSString *)imageUrl toZone:(BOOL)toZone
{
    SendMessageToQQReq *req = nil;

    if (shareToQQType == KSShareToQQTypeVideo) {
        QQApiVideoObject *videoObj = [QQApiVideoObject objectWithURL:[NSURL URLWithString:url]
                                                               title:title
                                                         description:description
                                                     previewImageURL:[NSURL URLWithString:imageUrl]];
        req = [SendMessageToQQReq reqWithContent:videoObj];
    } else if (shareToQQType == KSShareToQQTypeMusic){
        QQApiAudioObject *audioObj =
        [QQApiAudioObject objectWithURL:[NSURL URLWithString:url]
                                  title:title
                            description:description
                        previewImageURL:[NSURL URLWithString:imageUrl]];
        req = [SendMessageToQQReq reqWithContent:audioObj];
    } else if (shareToQQType == KSShareToQQTypeURL) {
        QQApiURLObject *urlObj = [QQApiURLObject objectWithURL:[NSURL URLWithString:url]
                                                         title:title description:
                                  description previewImageURL:[NSURL URLWithString:
                                                               imageUrl]
                                             targetContentType:QQApiURLTargetTypeNews]; // 给了一个NotSpe
        req = [SendMessageToQQReq reqWithContent:urlObj];
    }

    if (toZone) {
        [QQApiInterface SendReqToQZone:req];
    } else {
        //将内容分享到qq
        [QQApiInterface sendReq:req];
    }
}

- (void)shareInAPP:(KSShareToQQType)shareToQQType title:(NSString *)title url:(NSString *)url description:(NSString *)description image:(UIImage *)image toZone:(BOOL)toZone
{
    SendMessageToQQReq *req = nil;
    
    if (shareToQQType == KSShareToQQTypeVideo) {
        QQApiVideoObject *videoObj = [QQApiVideoObject objectWithURL:[NSURL URLWithString:url]
                                                               title:title
                                                         description:description
                                                    previewImageData:UIImageJPEGRepresentation(image, 1.0)];
        req = [SendMessageToQQReq reqWithContent:videoObj];
    } else if (shareToQQType == KSShareToQQTypeMusic){
        QQApiAudioObject *audioObj =
        [QQApiAudioObject objectWithURL:[NSURL URLWithString:url]
                                  title:title
                            description:description
                        previewImageData:UIImageJPEGRepresentation(image, 1.0)];
        req = [SendMessageToQQReq reqWithContent:audioObj];
    } else if (shareToQQType == KSShareToQQTypeURL || (shareToQQType == KSShareToQQTypeImage && toZone)) {
        QQApiURLObject *urlObj = [QQApiURLObject objectWithURL:[NSURL URLWithString:url]
                                                         title:title
                                                   description:description
                                              previewImageData:UIImageJPEGRepresentation(image, 1.0)
                                             targetContentType:QQApiURLTargetTypeNews]; // 给了一个NotSpe
        req = [SendMessageToQQReq reqWithContent:urlObj];
    } else if (shareToQQType == KSShareToQQTypeImage) {
        QQApiImageObject *imageObj = [QQApiImageObject objectWithData:UIImageJPEGRepresentation(image, 1.0) previewImageData:UIImageJPEGRepresentation(image, 1.0) title:title description:description];
        req = [SendMessageToQQReq reqWithContent:imageObj];
    }
    
    if (toZone) {
        [QQApiInterface SendReqToQZone:req];
    } else {
        //将内容分享到qq
        [QQApiInterface sendReq:req];
    }
}

- (void)shareToQQInAPP:(KSShareToQQType)shareToQQType title:(NSString *)title url:(NSString *)url description:(NSString *)description imageUrl:(NSString *)imageUrl withCompletion:(shareApiCompletionBlock)completion
{
    [self shareInAPP:shareToQQType title:title url:url description:description imageUrl:imageUrl toZone:NO];
    _shareCompletionBlock = completion;
}

- (void)shareToZoneInAPP:(KSShareToQQType)shareToQQType title:(NSString *)title url:(NSString *)url description:(NSString *)description imageUrl:(NSString *)imageUrl withCompletion:(shareApiCompletionBlock)completion;
{
    [self shareInAPP:shareToQQType title:title url:url description:description imageUrl:imageUrl toZone:YES];
    _shareCompletionBlock = completion;
}

- (void)shareToQQInAPP:(KSShareToQQType)shareToQQType title:(NSString *)title url:(NSString *)url description:(NSString *)description image:(UIImage *)image withCompletion:(shareApiCompletionBlock)completion
{
    [self shareInAPP:shareToQQType title:title url:url description:description image:image toZone:NO];
    _shareCompletionBlock = completion;
}

- (void)shareToZoneInAPP:(KSShareToQQType)shareToQQType title:(NSString *)title url:(NSString *)url description:(NSString *)description image:(UIImage *)image withCompletion:(shareApiCompletionBlock)completion;
{
    [self shareInAPP:shareToQQType title:title url:url description:description image:image toZone:YES];
    _shareCompletionBlock = completion;
}



/**
 *  微博登陆
 *
 *  @param completion Block返回
 */
- (void)loginByQQWithCompletion:(loginApiCompletionBlock)completion
{
//    NSArray *permissions = [NSArray arrayWithObjects:@"get_user_info", @"add_share", @"add_t", nil];
    NSArray *permissions = [NSArray arrayWithObjects:@"all", nil];
    [_tencentAuth authorize:permissions inSafari:NO];
    _loginCompletionBlock = completion;
}

#pragma mark - TencentSessionDelegate

- (void)tencentDidLogin {
    if (_tencentAuth.accessToken && 0 != [_tencentAuth.accessToken length]) {
        //  记录登录用户的OpenID、Token以及过期时间
        NSLog(@"tencentDidLogin: %@", [_tencentAuth debugDescription]);
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
        NSString *expirationDateString = [dateFormatter stringFromDate:_tencentAuth.expirationDate];
        
//        NSString *expirationDateString = [NSString stringWithFormat:@"%f", [_tencentAuth.expirationDate timeIntervalSince1970]];
        
        if (_loginCompletionBlock) {
            _loginCompletionBlock(YES, _tencentAuth.accessToken, _tencentAuth.openId, expirationDateString);
        }
    } else {
        NSLog(@"%@",@"登录不成功 没有获取accesstoken");
        if (_loginCompletionBlock) {
            _loginCompletionBlock(NO, nil, nil, nil);
        }
    }
}


- (void)getUserInfoResponse:(APIResponse*) response{
    NSLog(@"QQresponse:%@", response.description);

    if (_nameCompletionBlick) {
        _nameCompletionBlick(YES, [response.jsonResponse objectForKey:@"nickname"]);
    }
}

-(void)tencentDidNotNetWork {
    NSLog(@"%@",@"There's not newwork");
}

-(void)tencentDidNotLogin:(BOOL)cancelled {
    if (cancelled) {
        NSLog(@"%@",@"canceled");
    }else{
        NSLog(@"%@",@"didn't login");
    }
//    [KSAlertView dismiss];
}

-(void)tencentDidLogout {
    NSLog(@"%@",@"logout");
}

#pragma mark QQApiInterfaceDelegate
/**
 处理来至QQ的请求
 */
- (void)onReq:(QQBaseReq *)req {
    NSLog(@"onReq......");
}

//- (void)onRespForQQ:(QQBaseResp *)resp {
//    if ([resp.result isEqualToString:@"0"]) {
//        if (_shareCompletionBlock) {
//            _shareCompletionBlock(YES);
//            _shareCompletionBlock = nil;
//        }
//        return;
//    }
//}

- (void)onResp:(QQBaseResp *)resp {
    if ([resp.result isEqualToString:@"0"]) {
        if (_shareCompletionBlock) {
            _shareCompletionBlock(YES);
            _shareCompletionBlock = nil;
        }
        return;
    }
}

- (void)isOnlineResponse:(NSDictionary *)response {
    
}


@end
